<template>
  <div class="app-container">
    <div class="apikey-content">
      <div class="page-header">
        <h1>我的API密钥</h1>
        <el-button type="primary" icon="el-icon-plus" @click="handleGenerateKey">生成新密钥</el-button>
      </div>

      <!-- API密钥列表 -->
      <el-table
        v-loading="loading"
        :data="apiKeyList"
        style="width: 100%"
        border>
        <el-table-column
          prop="name"
          label="密钥名称"
          min-width="120">
        </el-table-column>
        <el-table-column
          prop="apiKey"
          label="Access Key"
          min-width="220">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.apiKey" placement="top">
              <span>{{ scope.row.apiKey }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="dailyLimit"
          label="每日调用限制"
          width="120">
        </el-table-column>
        <el-table-column
          prop="qpsLimit"
          label="QPS限制"
          width="100">
        </el-table-column>
        <el-table-column
          prop="expireTime"
          label="过期时间"
          width="120">
          <template slot-scope="scope">
            {{ parseTime(scope.row.expireTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
          fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewDetail(scope.row)">
              详情
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-copy-document"
              @click="handleCopyKey(scope.row)">
              复制
            </el-button>
            <el-popconfirm
              title="确定删除该密钥吗？"
              @confirm="handleDelete(scope.row)"
            >
              <el-button
                slot="reference"
                size="mini"
                type="text"
                icon="el-icon-delete"
                style="color: #F56C6C;">
                删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 密钥生成对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="密钥名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入密钥名称"></el-input>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="form.expireTime"
            type="datetime"
            placeholder="选择过期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="每日调用限制" prop="dailyLimit">
          <el-input-number v-model="form.dailyLimit" :min="100" :max="1000000" style="width: 100%;"></el-input-number>
        </el-form-item>
        <el-form-item label="QPS限制" prop="qpsLimit">
          <el-input-number v-model="form.qpsLimit" :min="1" :max="100" style="width: 100%;"></el-input-number>
        </el-form-item>
        <el-form-item label="IP白名单" prop="whiteIps">
          <el-input v-model="form.whiteIps" placeholder="多个IP用逗号分隔，留空表示不限制"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 密钥详情对话框 -->
    <el-dialog title="密钥详情" :visible.sync="detailVisible" width="600px">
      <div v-if="detailForm">
        <el-descriptions border :column="1">
          <el-descriptions-item label="密钥名称">{{ detailForm.name }}</el-descriptions-item>
          <el-descriptions-item label="Access Key">{{ detailForm.apiKey }}</el-descriptions-item>
          <el-descriptions-item label="每日调用限制">{{ detailForm.dailyLimit }} 次/天</el-descriptions-item>
          <el-descriptions-item label="QPS限制">{{ detailForm.qpsLimit }} 次/秒</el-descriptions-item>
          <el-descriptions-item label="过期时间">{{ parseTime(detailForm.expireTime) }}</el-descriptions-item>
          <el-descriptions-item label="IP白名单">{{ detailForm.whiteIps || '不限制' }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ detailForm.status === 1 ? '启用' : '禁用' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ parseTime(detailForm.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ detailForm.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="api-usage-example" v-if="detailForm">
        <h3>API调用示例</h3>
        <pre>curl -X POST "https://api.example.com/your-api-endpoint" \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: {{ detailForm.apiKey }}" \
  -d '{"param1": "value1", "param2": "value2"}'</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMyApiKeys, generateApiKey, updateApiKeyStatus, deleteApiKey } from '@/api/front'
import { parseTime } from '@/utils'
import Clipboard from 'clipboard'

export default {
  name: 'ApiKeys',
  data() {
    return {
      loading: false,
      total: 0,
      apiKeyList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '生成API密钥',
      submitLoading: false,
      detailVisible: false,
      detailForm: null,
      form: {
        name: '',
        dailyLimit: 10000,
        qpsLimit: 10,
        expireTime: '',
        whiteIps: '',
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入密钥名称', trigger: 'blur' },
          { min: 2, max: 30, message: '密钥名称长度在2到30个字符之间', trigger: 'blur' }
        ],
        expireTime: [
          { required: true, message: '请选择过期时间', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    // 设置默认过期时间为一年后
    const date = new Date()
    date.setFullYear(date.getFullYear() + 1)
    this.form.expireTime = parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}')
  },
  methods: {
    parseTime,
    getList() {
      this.loading = true
      getMyApiKeys().then(response => {
        this.apiKeyList = response.rows.map(item => {
          return {
            ...item,
            showSecret: false
          }
        })
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('获取数据失败')
      })
    },
    toggleSecretDisplay(row) {
      this.$set(row, 'showSecret', !row.showSecret)
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    handleViewDetail(row) {
      this.detailForm = JSON.parse(JSON.stringify(row))
      this.detailVisible = true
    },
    handleCopyKey(row) {
      const clipboard = new Clipboard('.copy-btn', {
        text: () => `API Key: ${row.apiKey}`
      })
      
      // 创建一个临时按钮并点击它
      const button = document.createElement('button')
      button.className = 'copy-btn'
      document.body.appendChild(button)
      button.click()
      document.body.removeChild(button)
      
      clipboard.on('success', e => {
        this.$message.success('API密钥已复制到剪贴板')
        clipboard.destroy()
      })
      
      clipboard.on('error', e => {
        this.$message.error('复制失败，请手动复制')
        clipboard.destroy()
      })
    },
    handleGenerateKey() {
      this.dialogTitle = '生成API密钥'
      this.dialogVisible = true
      this.resetForm()
    },
    handleStatusChange(row) {
      updateApiKeyStatus(row.id, row.status).then(() => {
        this.$message.success(`密钥状态已${row.status === 1 ? '启用' : '禁用'}`)
      }).catch(() => {
        // 状态切换失败时恢复原状态
        row.status = row.status === 1 ? 0 : 1
        this.$message.error('状态更新失败')
      })
    },
    handleDelete(row) {
      deleteApiKey(row.id).then(() => {
        this.$message.success('密钥已删除')
        this.getList()
      }).catch(() => {
        this.$message.error('删除失败')
      })
    },
    resetForm() {
      this.form = {
        name: '',
        dailyLimit: 10000,
        qpsLimit: 10,
        expireTime: parseTime(new Date().setFullYear(new Date().getFullYear() + 1), '{y}-{m}-{d} {h}:{i}:{s}'),
        whiteIps: '',
        remark: ''
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true
          generateApiKey(this.form).then(response => {
            this.$message.success('API密钥生成成功')
            this.dialogVisible = false
            this.getList()
            this.submitLoading = false
          }).catch(() => {
            this.submitLoading = false
            this.$message.error('API密钥生成失败')
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .apikey-content {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0,21,41,.08);

    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h1 {
        margin: 0;
        font-size: 24px;
        color: #303133;
      }
    }

    .pagination-container {
      text-align: center;
      margin-top: 20px;
    }
  }

  .api-usage-example {
    margin-top: 20px;
    padding: 15px;
    background-color: #f9f9f9;
    border-radius: 4px;

    h3 {
      margin-top: 0;
      margin-bottom: 10px;
      font-size: 16px;
      color: #333;
    }

    pre {
      background-color: #f5f5f5;
      padding: 10px;
      border-radius: 4px;
      overflow-x: auto;
      font-family: 'Courier New', Courier, monospace;
      font-size: 13px;
      line-height: 1.5;
      color: #333;
      border: 1px solid #e0e0e0;
    }
  }
}

::v-deep .el-table {
  .el-tooltip {
    display: block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style> 